package com.roin.learn.dwr;

import java.util.Map;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;

import com.roin.learn.dwr.listener.DWRScriptSessionListener;

public class MessagePush {
	public static String TAG="MessagePush_Tag";

	public void send(String msg) {
		//执行推送
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			
			@Override
			public boolean match(ScriptSession scriptSession) {
				String tag = (String) scriptSession.getAttribute("tag");
				System.out.println(tag);
				return TAG.equals(tag);
			}
		},new Runnable() {
			
			@Override
			public void run() {
				ScriptBuffer scriptBuffer = new ScriptBuffer();
				//设置要调用的js函数以及参数
				scriptBuffer.appendCall("show", msg);
				//获取所有的ScriptSession
				Map<String, ScriptSession> sessions = DWRScriptSessionListener.getScriptsessionmap();
				for (ScriptSession scriptSession : sessions.values()) {
					scriptSession.addScript(scriptBuffer);
				}
			}
		});
	}
	
	//在页面加载时调用这个方法，来绑定tag
	public void onPageLoad(String tag){
		//获取当前的ScriptSession
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("tag", tag);
		System.out.println("set tag attribut ! tag is "+tag);
	}
	
	public String getTag(){
		return TAG;
	}
}
